/******************************************************************
 *
 *    Java Lib For JavaWeb, Powered By Shenzhen WEI YI KE JI .
 *
 *    Copyright (c) 2017-2027 Digital Telemedia Co.,Ltd
 *    http://www.d-telemedia.com/
 *
 *    Package:     com.theyeasy.dvmini.service.impl
 *
 *    Filename:    ProjectServiceImpl.java
 *
 *    Description: TODO(用一句话描述该文件做什么)
 *
 *    Copyright:   Copyright (c) 2017-2027
 *
 *    Company:     Theyeasy Telemedia Co.,Ltd
 *
 *    @author:     hm
 *
 *    @version:    1.0.0
 *
 *    Create at:   2017年10月22日 下午5:53:36
 *
 *    Revision:
 *
 *    2017年10月22日 下午5:53:36
 *        - first revision
 *
 *****************************************************************/
package com.theyeasy.dvmini.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.theyeasy.weixin.model.WxMiniSessionInfo;
import org.theyeasy.weixin.util.CusAccessObjectUtil;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.theyeasy.dvmini.dao.CalllogDao;
import com.theyeasy.dvmini.dao.FansDao;
import com.theyeasy.dvmini.dao.SalesDao;
import com.theyeasy.dvmini.model.Calllog;
import com.theyeasy.dvmini.model.Fans;
import com.theyeasy.dvmini.model.Sales;
import com.theyeasy.dvmini.service.FansService;
import com.theyeasy.dvmini.service.SalesService;
import com.theyeasy.dvmini.util.CommonUtil;
import com.theyeasy.dvmini.util.PageResults;
import com.theyeasy.dvmini.util.StringUtil;
import com.theyeasy.dvmini.vo.Calllog_Vo;
import com.theyeasy.dvmini.vo.Fans_Vo;

import tk.mybatis.mapper.entity.Example;

/**
 * @ClassName ProjectServiceImpl
 * @Description TODO(这里用一句话描述这个类的作用)
 * @author hm
 * @Date 2017年10月22日 下午5:53:36
 * @version 1.0.0
 */
@Service
public class FansServiceImpl implements FansService {

    @Autowired
    FansDao fansDao;
    
    @Autowired
    CalllogDao callLogDao;

    @Autowired
    SalesDao salesDao;
    
    @Autowired
    SalesService salesService;
    /*
     * (非 Javadoc) Description:fans列表
     * @see com.theyeasy.dvmini.service.FansService#getFansList(java.lang.Integer, java.lang.String)
     */
    @Override
    public PageResults<Fans_Vo> getFansList(Integer page, String keyword) {
        List<Fans_Vo> list = fansDao.getFansList((page - 1) * 10, 10, keyword);
        int total = fansDao.getFansCount(keyword);
        PageResults<Fans_Vo> pageResults = new PageResults<>();
        pageResults.setPage(page);
        pageResults.setPageSize(10);
        pageResults.setRows(list);
        pageResults.setTotal(total);
        return pageResults;
    }

    /*
     * (非 Javadoc) Description:
     * @see com.theyeasy.dvmini.service.FansService#getFansByMiniOpenid(java.lang.String)
     */
    @Override
    public Fans getFansByMiniOpenid(String miniOpenid) {
        Example example = new Example(Fans.class);
        example.createCriteria().andEqualTo("miniopenid", miniOpenid);
        List<Fans> list = fansDao.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public Fans getFansById(Integer id) {
         
        return fansDao.selectByPrimaryKey(id);
    }
 
    @Override
    public String addCallLog(Integer fansid, Integer saleid,String projectname) {
        Calllog log=new Calllog();
         log.setFansid(fansid);
         log.setSalesid(saleid);
         log.setCreatedtime(CommonUtil.getTime());
         log.setProjectname(projectname);
         int row = callLogDao.insertSelective(log);
         return row>0?"ok":"添加失败，数据异常";
    }

    @Override
    public PageResults<Calllog_Vo> getCalllogList(int page, String keyword) {
        List<Calllog_Vo> list=callLogDao.getCalllogList((page-1)*10, 10, keyword);
        int total=callLogDao.getCalllogCount(keyword);
        PageResults<Calllog_Vo>  pageresult=new PageResults<>();
        pageresult.setPage(page);
        pageresult.setRows(list);
        pageresult.setPageSize(10);
        pageresult.setTotal(total);
        return pageresult;
    }

	@Override
	public Fans addFans(String miniOpenid) {
		Fans fans = getFansByMiniOpenid(miniOpenid);
		if (null!=fans) return fans;

		fans = new Fans();
		fans.setMiniopenid(miniOpenid);
		fans.setCreatedtime(CommonUtil.getTime());
		fans.setFanstype(1);
		fans.setLastlogintime(CommonUtil.getTime());
		fans.setLogo("");
		fans.setNickname("");
		fans.setParentfansid(0);
		fans.setSalesid(0);
		int flag = fansDao.insertSelective(fans);
		return fans;//插入成功后会返回新的id;
				
	}	
	
	 @Override
	    public Fans addFans(WxMiniSessionInfo info,Integer shareFansId,String nickname,String logo,Integer salesid, double lng, double lat) {
	    	 
	        if (info == null)
	            return null;
	        if (Strings.isNullOrEmpty(info.getOpenid()))
	            return null;
	        
	        //通过转发进来，获取转发者的销售id 
	        if(!StringUtil.isZearoOrNull(shareFansId)){
	            Fans sharefans=getFansById(shareFansId);
	            if(sharefans!=null && !StringUtil.isZearoOrNull(sharefans.getSalesid())){
	                salesid=sharefans.getSalesid();
	            }
	           
	        }
	        
	     /*   Sales sales = salesService.getSaleByMiniOpenId(info.getOpenid());
	        if(sales!=null) {
	        	salesid = sales.getId();
	        }*/
	        
	        // 判断粉丝是否存在
	        System.out.println("miniopenid:" + info.getOpenid());
	        Fans myfans = getFansByMiniOpenid(info.getOpenid());
	        
	        Fans fans = null;
	        try {
	            if (myfans == null) {
	                fans = new Fans();
	                fans.setCreatedtime(CommonUtil.getTime());
	                fans.setLastlogintime(CommonUtil.getTime());
	                fans.setMiniopenid(info.getOpenid());
	                fans.setParentfansid(shareFansId);
	                fans.setSalesid(salesid);
	                fans.setLogo(logo);
	                fans.setNickname(nickname);
	                fans.setFanstype(1);
	                fans.setLng(lng);
	                fans.setLat(lat);
	                JSONObject locationResult = CusAccessObjectUtil.locationResult(114.057869, 22.543099);
	                fans.setProvince(CusAccessObjectUtil.getProvince(locationResult));
	                fans.setCity(CusAccessObjectUtil.getCity(locationResult));
	                fans.setDistrict(CusAccessObjectUtil.getDistrict(locationResult));
	                fansDao.insertSelective(fans);
	            } else {
	                fans = new Fans();
	                fans.setId(myfans.getId());
	                fans.setLastlogintime(CommonUtil.getTime());
	                fans.setSalesid((StringUtil.isZearoOrNull(myfans.getSalesid())?salesid:myfans.getSalesid()));
	                fans.setNickname(nickname);
	                fans.setLogo(logo);
	                fans.setLng(lng);
	                fans.setLat(lat);
	                fans.setLng(lng);
	                fans.setLat(lat);
	                JSONObject locationResult = CusAccessObjectUtil.locationResult(114.057869, 22.543099);
	                fans.setProvince(CusAccessObjectUtil.getProvince(locationResult));
	                fans.setCity(CusAccessObjectUtil.getCity(locationResult));
	                fans.setDistrict(CusAccessObjectUtil.getDistrict(locationResult));
	                fans.setFormattedAddress(CusAccessObjectUtil.getFormattedAddress(locationResult));
	                fansDao.updateByPrimaryKeySelective(fans);
	            }
	        } catch (Exception e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            System.out.println("新增粉丝失败：" + e.getMessage());
	            return null;
	        }
	        
	       
	        return fans;
	    }
}
